package com.blackshadowgame.rps.slice;

import com.blackshadowgame.rps.*;
import com.blackshadowgame.rps.client.GameClient;
import com.blackshadowgame.utils.LogUtil;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.utils.IntervalTimer;

public class WaitingSlice extends BaseSlice implements Component.ClickedListener {
    private static final String TAG = WaitingSlice.class.getSimpleName();
    public String getTag(){
        return TAG;
    }

    protected int getLayoutId(){
        return ResourceTable.Layout_ability_main_waiting_slice;
    }

    protected int getTextLogId(){
        return ResourceTable.Id_text_info;
    }
    private IntervalTimer gameTimer = null;

    private Text txtResult = null;
    private boolean readyToStart = false;
    private Text txtService = null;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);

        addInfo("准备出拳，你的id是: " + GameClient.getInstance().getPlayerId());
        startGameLoop();
    }

    protected void initUIComponent() {
        super.initUIComponent();

        ((Button)findComponentById(ResourceTable.Id_buttonPlayWithAI)).setClickedListener(this);
        ((Button)findComponentById(ResourceTable.Id_buttonStopGame)).setClickedListener(this);

        ((Button)findComponentById(ResourceTable.Id_buttonStopGame)).setClickedListener(this);

        txtResult = (Text)findComponentById(ResourceTable.Id_text_result);
        txtService = (Text)findComponentById(ResourceTable.Id_text_service);
        txtResult.setText("开始游戏");
    }

    @Override
    public void onClick(Component component) {
        int id = component.getId();
        switch (id){
            case ResourceTable.Id_buttonPlayWithAI:
                onPlayWithAI();
                break;
            case ResourceTable.Id_buttonStopGame:
                onStopGame();
                break;
        }
    }

    private void onPlayWithAI(){
        int code = GameClient.getInstance().playWithAI();
        if(code != GameCode.ERR_OK){
            addInfo("加入AI玩家，失败： " + code);
        }else {
            addInfo("加入AI玩家");
        }
    }

    private void startGame(){
        if(!readyToStart){
            addInfo("游戏人数还不够，你可以选择与AI对决");
            return;
        }

        addInfo("正式开始游戏...");
        if(gameTimer != null){
            gameTimer.cancel();
            gameTimer = null;
        }
        goGamePlaySlice();
    }

    private void onStopGame(){
        addInfo("退出游戏");
        if(gameTimer != null){
            gameTimer.cancel();
            gameTimer = null;
        }

        GameClient.getInstance().leaveGame();
//        GameClient.getInstance().disconnect();
        goHomeSlice();
    }

    private void startGameLoop(){
        if(gameTimer == null){
            gameTimer = new IntervalTimer(1000, 1000) {
                @Override
                public void onInterval(long l) {
                    runInMainThread(new Runnable() {
                        @Override
                        public void run() {
                            onLoop(l);
                        }
                    });
                }

                @Override
                public void onFinish() {
                    gameTimer.schedule();
                }
            };
            gameTimer.schedule();
        }
    }

    public void runInMainThread(Runnable task){
        EventRunner runner = EventRunner.getMainEventRunner();
        EventHandler handler = new EventHandler(runner);
        handler.postTask(task);
    }

    protected void onLoop(long deltaTime){
        txtService.setText("游戏服务:" + GameClient.getInstance().getServiceName() + ", ID: " + GameClient.getInstance().getPlayerId());
        if(!GameClient.getInstance().isConnected()){
            addInfo("====> 连接断开！！！");
            goHomeSlice();
            return;
        }

        if(!readyToStart) {
            GameResultData result = GameClient.getInstance().queryGameResult();
            if(result.state == GameCode.GAME_STATE_NEW){
                addInfo("新游戏开始...");
            }else if(result.state == GameCode.GAME_STATE_WAITING_FOR_PLAYER){
                addInfo("等待其他玩家进入游戏...");
            }else if(result.state == GameCode.GAME_STATE_WAITING_FOR_INPUT){
                addInfo("玩家已经到齐，准备开始游戏...");
                String info = "";
                for(GameInput player: result.playerInputs){
                    info += String.format("玩家[%d] ", player.playerId);
                }
                addInfo(info);
                txtResult.setText(info);

                readyToStart = true;
            }else if(result.state == GameCode.GAME_STATE_FINISHED){
                // 不应该进入状态
            }else{
                // 其他未知状态
            }
        }else{
            // 准备开始游戏
            startGame();
        }
    }
}
